<template>
	<view class="container">
		<u-loading-page :loading="loading" loading-text="加载中..."></u-loading-page>
		<view class="view-main" v-if="!loading">
			<!-- 背景图 -->
			<view class="view-title">
				<image src="../../static/main/home_back.png"></image>
				<!-- <image :src="downloadBkPic('homeBg1')"></image> -->
			</view>
			<view class="title-content" :style="[{ top: titleTop }, { lineHeight: titleLineHeight }]">
				<div class="searchbox" @click="onSearchBoxClick">
					<u-icon name="search" color="#fff" size="28"></u-icon>
				</div>
				<div class="title-text">
					<image style="width: 38rpx;height: 38rpx;margin-right: 8rpx;" src="../../static/main/logo.png">
					</image>
					{{ title }}
				</div>
			</view>

			<!-- 搜索栏 -->
			<!-- <view class="notice">
				<view class="noticeBgBox">
	
				</view>
				<view class="notice-content" >
					<view v-if="noticeList.length===0"></view>
					<swiper v-else vertical="true" autoplay="true" circular="true" style="width:86%;height: 70rpx"
						interval=6000>
						<swiper-item @tap.stop="onNotice(item)" v-for="(item,index) in noticeList" :key="index">
							<view>{{item.searchName}}</view>
						</swiper-item>
					</swiper>
				</view>
			</view> -->
			<!-- 搜索栏下边模块 -->
			<view class="view-modules">
				<view class="modules-content flex justify-around">

					<view class="func-account cflex"
						@click="navigateApplet('wx4093c19683c4d6ff', '/pages/home/index?pageId=1305')">
						<div class="img-box">
							<image class="func-style" src="../../static/main/home-icon-1.png"></image>
						</div>
						<text class="color-white">账户服务</text>
					</view>
					<view class="func-account cflex"
						@click="navigateApplet('wx4093c19683c4d6ff', '/pages/home/index?pageId=1004')">
						<div class="img-box">
							<image class="func-style" src="../../static/main/home-icon-2.png"></image>
						</div>
						<text class="color-white">预约开户</text>
					</view>
					<view class="func-account cflex"
						@click="navigateApplet('wx4093c19683c4d6ff', '/pages/home/index?pageId=1221')">
						<div class="img-box">
							<image class="func-style" src="../../static/main/home-icon-3.png"></image>
						</div>
						<text class="color-white">网点查询</text>
					</view>
					<view class="func-account cflex" @click="navigateWebView">
						<div class="img-box">
							<image class="func-style" src="../../static/main/home-icon-4.png"></image>
						</div>
						<text class="color-white">一键测额</text>
					</view>
				</view>
			</view>

			<!-- 新闻资讯 -->
			<!-- 轮播图 -->
			<view class="addsBox">
				<u-swiper ref="swipeAD" :list="ADList" indicator indicatorMode="line" indicatorActiveColor="#B0C93E"
					circular height="100%" width="100%" @click="onAdClick" circular radius="200"
					interval=3000></u-swiper>
			</view>
			<view class="announce-box-container">
				<view class="content module-content-modal">
					<div class="announce-box">
						<image src="../../static/main/announce-icon.png"></image>
					</div>
					<!-- <view v-for="(row,index) in informationList" :key="index" @click="navigateToAnnounceDetail(row)">{{ row.title }}</view> -->
					<swiper vertical="true" autoplay="true" circular="true"
						style="width:100%;height: 70rpx;padding-right: 40rpx;" interval=6000>
						<swiper-item v-for="(row, index) in informationList" :key="index"
							@click="navigateToAnnounceDetail(row)">
							<view class=" main-title">
								<span class="ellipsis text" style="flex:1">{{ row.title }}</span>
								<span class="label hot" v-if="row.topping">热门</span>
								<span class="label new" v-if="row.newFlag">最新</span>
							</view>
						</swiper-item>
					</swiper>
					<div class="more" @click="onMoreAnnounceBtnClick">
						<image src="../../static/main/more.png"></image>
					</div>
				</view>
			</view>

			<!-- <view class="getMoreBox" @click="onMoreAnnounceBtnClick">
					<text>更多资讯</text>
					<image src="../../static/index/rightArrow.png"></image>
				</view> -->

			<view class="getMoreBox" @click="onGetMoreSchemeBtnClick">
				<div class="left">
					<div class="line-mark"></div>
					<view class="middleTitle">
						<image src="../../static/index/rank1.png"></image>
					</view>
				</div>
				<div class="right">更多
					<div class="arrow-box">
						<image src="../../static/main/arrow.png"></image>
					</div>
				</div>

			</view>
			<view class="view-button-main">
				<view v-for="(item, index) in schemeList" :key="index" @click="onSchemeItemClick(item)">
					<image :src="item.img" />
					<view class="text">
						<text>{{ item.name }}</text>
						<text style="color: rgba(74, 74, 74, 1);font-size: 24rpx;">点击查看详情</text>
					</view>
				</view>

			</view>



			<!-- <view class="middleTitle">
				<image src="../../static/index/rank2.png"></image>
			</view> -->
			<view class="getMoreBox" @click="onMoreProductBtnClick">
				<div class="left">
					<div class="line-mark"></div>
					<view class="middleTitle">
						<image src="../../static/index/rank2.png"></image>
					</view>

				</div>
				<div class="right">更多
					<div class="arrow-box">
						<image src="../../static/main/arrow.png"></image>
					</div>
				</div>
			</view>

			<view class="rantListBox">
				<div class="top">
					<div class="back">
						<image src="../../static/main/productRank.png"></image>
					</div>
					<div class="isTop first" @click="onProductItemClick(rantList[0])">
						<div class="title">{{ rantList[0].name }}</div>
						<div class="desc">{{ rantList[0].nameIntroduction || '点击查看详情' }}</div>
					</div>
					<div class="isTop second" @click="onProductItemClick(rantList[1])">
						<div class="title">{{ rantList[1].name }}</div>
						<div class="desc">{{ rantList[1].nameIntroduction || '点击查看详情' }}</div>
					</div>
					<div class="isTop third" @click="onProductItemClick(rantList[2])">
						<div class="title">{{ rantList[2].name }}</div>
						<div class="desc">{{ rantList[2].nameIntroduction || '点击查看详情' }}</div>
					</div>
				</div>
				<div class="list-content">
					<view class="item-content" v-for="(item, index) in restProductRankList" :key="index"
						@click="onProductItemClick(item)">
						<view class="rantItemLeftBox">
							<text>
								{{ index + 4 }}
							</text>
							<!-- <image v-if="index == 0" :src="downloadBkPic('rent1')"></image>
							<image v-else-if="index == 1" :src="downloadBkPic('rent2')"></image>
							<image v-else-if="index == 2" :src="downloadBkPic('rent3')"></image> -->

						</view>
						<view class="rantItemRightBox">
							<view class="title">{{ item.name }}</view>
							<text>{{ item.nameIntroduction || '点击查看详情' }}</text>
						</view>

						<!-- <image class="bgRantImg" mode="heightFix" v-if="index == 0" src="../../static/index/rant11.png"></image>
						<image class="bgRantImg" mode="heightFix" v-else-if="index == 1" src="../../static/index/rant22.png">
						</image>
						<image class="bgRantImg" mode="heightFix" v-else-if="index == 2" src="../../static/index/rant33.png">
						</image> -->
					</view>
				</div>
			</view>

			<view class="bottom-space">
			</view>
			<view class="popupImgBox" v-if="showPopupImg">
				<image :src="download(popupMsg.popup)" @click="onPopupImgClick" mode="">
				</image>
				<view class="closeImgBox" @click="onPopupClose">
					<u-icon name="close-circle" size="34" color="#fff"></u-icon>
				</view>
			</view>
			<view class="mask" v-if="showMask"></view>
			<view class="videoBox" v-if="isVideoShow" @click="onVideoClose" :catchtouchmove='isVideoShow'>
				<video @tap.stop :src="videoUrl" :poster="videoPicUrl" object-fit="fill" :custom-cache="false"></video>
			</view>
			<!-- 机器人入口 -->
			<!-- <view class="chatBox" @click="onChatClick">
				<img src="../../static/mine/robot.png" alt="">
			</view> -->
			<!-- 新人首次登录弹窗 -->
			<popLogin :isShow='showAuth' @onreject="onreject" @onLoginConfirm="onLoginConfirm"></popLogin>
		</view>
	</view>

</template>

<script>
	import {
		isEmpty,
		baseURL,
		formatMoney,
		download,
		downloadBkPic,
		downloadVideo
	} from "@/utils/util.js";
	import {
		getPhone,
		login,
		hotSearch,
		queryHomeDisplaySolution,
		queryAllPic,
		queryKeyProduction,
		queryHomeDisplaySolutionTypeName,
		queryByOpenId,
		queryInformation3,
		queryNewestMessage,
		addMessageToCurrentMessage,
		queryPublicKey
	} from "@/apis/index.js";

	import {
		updateReadFlag
	} from '@/apis/message.js'

	import popLogin from "@/components/popLogin.vue"
	import Encrypt from '@/utils/aesUtil'
	import {
		envVersion,
		getH5Url
	} from "../../utils/util";

	export default {
		onShareAppMessage(res) {
			return {
				title: this.title,
				path: '/pages/index/index'
			}
		},
		components: {
			popLogin
		},
		data() {
			return {
				baseURL,
				showPopupImg: false, // 弹窗广告
				popupMsg: {}, // 弹窗广告数据
				title: '邮储银行公司金融易企典',
				ADList: [],
				adMsgArr: [], // 轮播数据
				schemeList: [], // 特色场景帮
				loading: true,
				showMask: false,
				showAuth: false,
				videoUrl: '',
				videoPicUrl: '',
				isVideoShow: false,
				// authPrompt: '',
				// curAuth: '',
				// nickName: '微信用户',
				// haveLogin: false,
				// canIUseGetUserProfile: true,
				imageList: [{
					src: `${baseURL}/applet/image?name=homeBg`,
					file: ''
				}],
				noticeList: [], // 热搜
				rantList: [],
				titleTop: '0px',
				titleLineHeight: '0px',
				loginPhone: '',
				nextOptionFunc: '',
				informationList: [{
						id: 1,
						title: 'xxxxxxxxxxxx测试数据xxxxxxxxxx',
						content: '嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻信息'
					},
					{
						id: 2,
						title: 'xxxxxxxxxxxx测试数据xxxxxxxxxx',
						content: '嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻信息'
					},
					{
						id: 3,
						title: 'xxxxxxxxxxxx测试数据xxxxxxxxxx',
						content: '嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻信息'
					},
				]
			}
		},
		onReady() {
			let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
			this.titleTop = menuButtonInfo.top.toString() + 'px';
			this.titleLineHeight = menuButtonInfo.height.toString() + 'px';
		},
		onLoad() {
			this.getQuekLogin() // 静默登录
			// this.getHomeSearchMsg()
			// this.getSchemaMsg()
			// this.getAdsSwiperMsg()
			// this.getProductMsg()
			this.getNewestMsg()
			this.queryInformation()
			uni.setStorageSync('needLogin', false) // 页面初始化不需要登录
		},
		onShow() {
			console.log('-----');
			if (uni.getStorageSync('needLogin')) { // 从其他页面来 需要登录的情况
				this.onLoginBtnClick()
			}
		},
		computed: {
			restProductRankList() {
				return this.rantList.splice(3)
			}
		},
		methods: {
			downloadBkPic,
			download,
			async navigateWebView() {
				if (!uni.getStorageSync('token')) { // 如果页面没token 需要登录
					this.onLoginBtnClick()
					return
				}
				const hasExpired = await this.judgeHasExpired()
				if (hasExpired) {
					this.onLoginBtnClick()
					return
				}
				// uni.showToast({
				// 	icon: 'none',
				// 	title: '该功能将于近期开放，敬请期待'
				// })
				// return
				const secretPhone = uni.getStorageSync('h5EncryptPhone')
				if (!secretPhone) {
					const result = await queryPublicKey()
					const cryptPhone = result?.data || ''
					if (!cryptPhone) {
						this.onLoginBtnClick()
						return
					}
					uni.setStorageSync('h5EncryptPhone', cryptPhone)
				}
				// let url = 'https://cbcbp.dev.psbc.com:8443/sit/xwyloan/#/home'
				// url += `?phone=${uni.getStorageSync('h5EncryptPhone')}`
				// url += `&promoChannel=77`
				// url += `&enterModel=01`

				let url = getH5Url(uni.getStorageSync('h5EncryptPhone'))
				uni.showModal({
					title: '',
					content: '即将打开小微e贷H5登录页面',
					confirmText: '允许',
					cancelText: '取消',
					success(resp) {
						console.log('resp: ', resp);
						if (!resp.confirm) return

						console.log('url: ', url);
						uni.navigateTo({
							url: '/pages/webView/webView?url=' + encodeURIComponent(url),
						})
					},
				})
			},
			// 跳转小程序
			async navigateApplet(appid, path, extraData) {
				const result = await queryPublicKey()
				const cryptPhone = result?.data || ''
				if (!cryptPhone) {
					this.onLoginBtnClick()
					return
				} else if (!uni.getStorageSync('token')) { // 如果页面没token 需要登录
					this.onLoginBtnClick()
					return
				} else {
					uni.navigateToMiniProgram({
						appId: appid,
						path,
						extraData,
						envVersion: envVersion == 'develop' ? 'trial' : envVersion
					})
				}
			},
			queryInformation() {
				queryInformation3().then((result) => {
					this.informationList = result.data
				});
			},
			onChatClick() {
				uni.navigateTo({
					url: '/pages/smartChat/smartChat'
				})
			},
			async judgeHasExpired() {
				const result = await queryPublicKey()
				const cryptPhone = result?.data || ''
				if (!cryptPhone) {
					return Promise.resolve(true)
				}
				uni.setStorageSync('h5EncryptPhone', cryptPhone)
				return Promise.resolve(false)
			},
			getQuekLogin() {
				uni.hideTabBar()
				// 先判断用户是否登陆过,不是新用户就直接调接口拿手机hao 静默登录
				const that = this
				if (uni.getStorageSync('phone')) {
					this.getLogin()
				} else {
					uni.login({
						success(res) {

							if (res.code) {
								//发起网络请求
								queryByOpenId(res.code).then(re => {

									if (re && re.data && re.data.loginName) {
										that.loginPhone = re.data.loginName
										uni.setStorageSync('phone', re.data.loginName);
										that.getLogin()
									} else { // 新用户
										that.getHomeSearchMsg()
										that.getSchemaMsg()
										that.getAdsSwiperMsg()
										that.getProductMsg()
										uni.showTabBar()
										that.loading = false
									}
								}).catch(e => {

								})

							} else {

							}
						}
					})
				}
			},
			getNewestMsg() {
				queryNewestMessage().then(res => {
					if (res && res.code == '00000000' && res.data) {
						this.popupMsg = res.data
						this.showPopupImg = true;
						this.showMask = true;
						uni.hideTabBar();
						uni.setStorageSync('longImgUrl', res.data.businessId)
					}
				})
			},
			onGetMoreSchemeBtnClick() {
				uni.switchTab({
					url: "/pages/scheme/scheme",
				})
			},
			onMoreAnnounceBtnClick() {
				if (!uni.getStorageSync('token')) { // 如果页面没token 需要登录
					this.onLoginBtnClick()
					return
				}
				uni.navigateTo({
					url: "/pages/announce/announce"
				})
			},
			onMoreProductBtnClick() {

				uni.switchTab({
					url: "/pages/product/product"
				})
			},

			navigateToAnnounceDetail(row) {
				console.log('row: ', row);
				if (!uni.getStorageSync('token')) { // 如果页面没token 需要登录
					this.onLoginBtnClick()
					return
				}
				uni.navigateTo({
					url: `/pages/announce/detail?id=${row.id}`
				})
			},
			getHomeSearchMsg() {
				hotSearch().then(res => {
					if (res.code == '00000000') {
						if (res.data && res.data.length) {
							this.noticeList = res.data
						}
					}
				})
			},
			getSchemaMsg() { // 特色场景榜
				queryHomeDisplaySolutionTypeName().then(res => {
					if (res.code == '00000000') {
						for (let [index, item] of res.data.entries()) {
							if (item == '专精特新') {
								this.schemeList[index] = {
									name: '专精特新',
									img: '../../static/main/zhuangjingtexin.png'
								}
							} else if (item == '建筑工程') {
								this.schemeList[index] = {
									name: '建筑工程',
									img: '../../static/main/jianzhu.png'
								}
							} else if (item == '政务民生') {
								this.schemeList[index] = {
									name: '政务民生',
									img: '../../static/main/zhengwuminsheng.png'
								}
							} else if (item == '企业经营') {
								this.schemeList[index] = {
									name: '企业经营',
									img: '../../static/main/qiyejingying.png'
								}
							}

						}
					}
				})
			},
			getAdsSwiperMsg() { // 轮播图
				queryAllPic().then(res => {
					if (res.code == '00000000') {
						this.ADList = []
						if (res.data && res.data.length) {
							this.adMsgArr = res.data
							for (let item of res.data) {
								this.ADList.push(download(item.pictureId))
							}
						}
					}
				})
			},
			onVideoClose() {
				this.isVideoShow = false
				this.showMask = false
				uni.showTabBar()
			},

			onAdClick(index) {
				if (!uni.getStorageSync('token')) { // 如果页面没token 需要登录
					this.onLoginBtnClick()
					return
				}

				const data = this.adMsgArr[index]
				if (data.videoId) {
					this.isVideoShow = true

					if (data.videoId == 'Z3JvdXAxL00wMC8yNi9BQy9GdUE3SVdYNXpTT0FEM19yQU9uTkJVNXBhVWsyMzQubXA0') {
						let urlvideo = `https://static.yqy.psbc.com/videos/${data.videoId}.mp4`
						let urlvideo2 = ''
						wx.request({
							url: `https://static.yqy.psbc.com/videos/${data.videoId}.mp4`, // 请求资源 报404就用以前的
							method: 'GET',
							success(res) {
								if (res.statusCode == 200) {

								} else {
									urlvideo = downloadVideo(data.videoId)
								}
							},
							fail(err) {
								urlvideo = downloadVideo(data.videoId)

							}
						});

						setTimeout(() => {
							this.videoUrl = urlvideo
							console.log(this.videoUrl, 123123);
						}, 800)
					} else {
						this.videoUrl = downloadVideo(data.videoId)
					}
							console.log(this.videoUrl, 22222);
					this.videoPicUrl = download(data.pictureId)
					this.showMask = true
					uni.hideTabBar()
				}
				if (data.businessType == 1) {
					uni.navigateTo({
						url: `/pages/product/productDetail?id=${data.businessId}`
					})
				} else if (data.businessType == 2) {
					uni.navigateTo({
						url: `/pages/scheme/schemeDetail?id=${data.businessId}`
					})
				}
			},
			getProductMsg() { // 特色产品榜
				queryKeyProduction().then(res => {
					if (res.code == '00000000') {
						this.rantList = res.data

					}
				})
			},
			onProductItemClick(item) {
				if (!uni.getStorageSync('token')) { // 如果页面没token 需要登录
					this.onLoginBtnClick()
					return
				}
				uni.navigateTo({
					url: '/pages/product/productDetail?id=' + item.id
				})
			},

			onreject() {
				// uni.setStorageSync('authUser', '');
				// uni.setStorageSync('authPhone', '');
				uni.setStorageSync('userInfo', '');
				uni.setStorageSync('phone', '');
				uni.setStorageSync('needLogin', false);
				this.nextOptionFunc = ''
				this.showAuth = false;
				// this.showMask = false;
				// this.curAuth = 'mobile';
				// uni.showTabBar();
			},
			onLoginConfirm() {
				this.showAuth = false
				this.getLogin('newPeople');
			},

			onLoginBtnClick() {
				// 如果是新用户 弹出登录框授权
				// this.curAuth = 'mobile';
				this.showAuth = true;
				// this.showMask = true;
				// uni.hideTabBar();
			},
			getLogin(val = '') {

				const that = this
				uni.login({
					provider: 'weixin',
					success: function(res) {

						let code = res.code;
						let phone = uni.getStorageSync('phone');

						let data = {
							phoneJsCode: uni.getStorageSync('phoneJsCode'),
							wechatJsCode: code,
							loginName: Encrypt.encrypt(phone)
							// name: nickName
						};
						login(data)
							.then((re) => {
								if (re.code == '00000000') {
									uni.setStorageSync('token', re.data.token);
									uni.setStorageSync('userMsg', re.data);

									that.getHomeSearchMsg()
									that.getSchemaMsg()
									that.getAdsSwiperMsg()
									that.getProductMsg()
									uni.showTabBar()
									that.loading = false
									if (val == 'newPeople' && that.popupMsg.id) {
										const params = {
											userId: re.data.userId,
											messageId: that.popupMsg.id
										}
										addMessageToCurrentMessage(params).then(r => {
											if (r.code == '00000000') {

											}
										})
									}
									if (val == 'newPeople' && that.nextOptionFunc == 'onPopupImgClick') {
										that.onPopupImgClick()
									}
								}
							})
							.catch((err) => {


							});
					}
				})
			},
			onPopupClose() {
				this.showPopupImg = false;
				this.showMask = false;
				uni.showTabBar();
			},
			onPopupImgClick() {
				if (!uni.getStorageSync('token')) {
					this.nextOptionFunc = 'onPopupImgClick'
					this.onPopupClose()
					this.onLoginBtnClick()
					return
				}
				this.onPopupClose()
				updateReadFlag({
					messageId: this.popupMsg.id
				}).then(res => { // 更新已读
					if (res.code == '00000000') {}
				})
				if (this.popupMsg.businessType == 1) {
					uni.navigateTo({
						url: `/pages/product/productDetail?id=${this.popupMsg.businessId}`
					})
				} else if (this.popupMsg.businessType == 2) {
					uni.navigateTo({
						url: `/pages/scheme/schemeDetail?id=${this.popupMsg.businessId}`
					})
				} else if (this.popupMsg.businessType == 3) {
					uni.navigateTo({
						url: `/pages/message/systemMessageDetail?title=${this.popupMsg.title}`
					})
				}
			},
			onSchemeItemClick(item) {
				if (!uni.getStorageSync('token')) { // 如果页面没token 需要登录
					this.onLoginBtnClick()
					return
				}
				uni.setStorageSync('indexToSchemeListName', item.name)
				uni.switchTab({
					url: '/pages/scheme/scheme'
				})
			},
			onNotice(item) {
				uni.navigateTo({
					url: `/pages/search/search?val=${item.searchName}`
				})
			},
			onSearchBoxClick() {
				uni.navigateTo({
					url: `/pages/search/search`
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	@import './index.scss';

	.func-account {
		image {
			width: 100rpx;
			height: 100rpx;
		}
	}
</style>